<template>

  <!---搜索表单-->
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="关键字">
            <el-input v-model ="userDto.keyword"
              style="width: 100%"
              placeholder="用户名"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间">
            <el-date-picker v-model="createTimes"
              type="daterange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="search">搜索</el-button>
        <el-button size="small" @click="reset">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <!--添加按钮-->
  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow" >添 加</el-button>
  </div>

  <!---数据表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="username" label="用户名" />
    <el-table-column prop="name" label="姓名" />
    <el-table-column prop="phone" label="手机" />
    <el-table-column prop="avatar" label="头像" #default="scope">
      <img :src="scope.row.avatar" width="50" />
    </el-table-column>
    <el-table-column prop="description" label="描述" />
    <el-table-column prop="status" label="状态" #default="scope">
      {{ scope.row.status == 1 ? '正常' : '停用' }}
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column label="操作" align="center" width="280" #default="scope">
      <el-button type="primary" size="small" @click="editShow(scope.row)">修改</el-button>
      <el-button type="danger" size="small" @click="delUser(scope.row)">删除</el-button>
      <el-button type="warning" size="small" @click="assignRoleShow(scope.row)">分配角色</el-button>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="userDto.pageNum"
    v-model:page-size="userDto.pageSize"
    :page-sizes="[5, 10, 20]"
    @size-change="getfindAllSysUser"
    @current-change="getfindAllSysUser"
    layout="total, sizes, prev, pager, next"
    :total="total"
  />


  <el-dialog v-model="dialogVisible" :title="saveOrUpdateUserTitle" width="40%">
    <el-form label-width="120px" >
      <el-form-item label="用户名">
        <el-input v-model="sysUser.username"/>
      </el-form-item>
      <el-form-item v-if="sysUser.id == null" label="密码">
        <el-input type="password" show-password v-model="sysUser.password"/>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="sysUser.name"/>
      </el-form-item>
      <el-form-item label="手机">
        <el-input v-model="sysUser.phone"/>
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8501/admin/system/file/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :headers="headers"
        >
          <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述">
        <el-input  v-model="sysUser.description"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog v-model="dialogRoleVisible" title="分配角色" width="40%">
    <el-form label-width="80px">
      <el-form-item label="用户名">
        <el-input disabled :value="sysUser.username"></el-input>
      </el-form-item>

      <el-form-item label="角色列表">
        <el-checkbox-group  v-model="userRoleIds">
          <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="assignRoleSubmit">提交</el-button>
        <el-button @click="dialogRoleVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<script setup>
import { ref, computed,watch,onMounted } from 'vue';
import {findAllSysUser,saveOrUpdateUser,deleteUser } from '@/api/system/sys-user';
import { ElMessage, ElMessageBox } from "element-plus";
import {allRole,assigningRoles} from '@/api/system/sys-role';
import {useApp} from "@/pinia/modules/app";


// 表格数据模型
const list = ref([
  {"id":1 , "username":"admin" , "name": "admin" , "phone":"13121034567" , "status":1 , "createTime": "2023-05-11"} ,
  {"id":2 , "username":"admin" , "name": "admin" , "phone":"13121034567" , "status":1 , "createTime": "2023-05-11"}
]);

const userRoleIds = ref([])

const allRoles = ref([
  {"id":1 , "roleName":"管理员"},
  {"id":2 , "roleName":"业务人员"},
  {"id":3 , "roleName":"商品录入员"},
])
// 分页条数据模型
const total = ref(0)
//事件搜索框数据
const createTimes = ref([])

const dialogVisible = ref(false)

const dialogRoleVisible = ref(false)

const saveOrUpdateUserTitle = ref("")

const sysUser = ref(
  {
    id: "",
    username:"",
    name: "" ,
    phone: "" ,
    password: "" ,
    description:"",
    avatar: ""
  })

//搜索数据模型
const userDto = ref({
  keyword:"",
  createTimeBegin: "",
  createTimeEnd: "",
  pageNum: 1,
  pageSize: 10

});

onMounted(() => {
  getfindAllSysUser();
});

const headers = {
  token: useApp().authorization.token     // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
}

//图片上传成功之后的回调
const handleAvatarSuccess =(response,uploadFile) =>{
  sysUser.value.avatar = response
}


const search =  () => {
    userDto.value.pageNum = 1;
    getfindAllSysUser();

}

//重置
const reset =  () => {
  userDto.value.keyword = "";
  createTimes.value = [];
  userDto.value.pageNum = 1;
  userDto.value.pageSize = 10;
  getfindAllSysUser();
}


const submit = async () => {
   const {message,code} = await saveOrUpdateUser(sysUser.value);
   if (code === 200){
    dialogVisible.value = false;
    getfindAllSysUser();
     ElMessage.success("操作成功");
  }else {
      ElMessage.error(message);
   }

}

const assignRoleShow = async (row) => {
  dialogRoleVisible.value = true;
  sysUser.value = row
  const {data} = await allRole(row.id);
  allRoles.value = data.sysRoleList;
  userRoleIds.value = data.sysRoleUserList
}

const editShow =  (data) => {
  dialogVisible.value = true;
  sysUser.value = data;
}

 const addShow =  () => {
  dialogVisible.value = true;
   saveOrUpdateUserTitle.value = "添加用户";
   sysUser.value.id =""
   sysUser.value.userName = "";
   sysUser.value.name = "";
   sysUser.value.phone = "";
   sysUser.value.password = "";
   sysUser.value.description = "";
   sysUser.value.avatar = "";
}

const delUser = async (data) => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const {code , message} = await deleteUser([data.id])
    if(code === 200) {
      ElMessage.success('删除成功')
      userDto.value.pageNum = 1
      getfindAllSysUser();
    }else {
      ElMessage.error(message)
    }
  })
}

//获取分页查询用户列表数据
const getfindAllSysUser = async () => {
 if (createTimes.value.length > 0){
   userDto.value.createTimeBegin = createTimes.value[0]
  userDto.value.createTimeEnd = createTimes.value[1]
 }
 const {data,code} = await findAllSysUser(userDto.value);
    list.value = data.records;
    total.value = data.total;
}

const assignRoleSubmit = async () => {
  let data ={
    userId :sysUser.value.id,
    roleIdList : userRoleIds.value
  }
  const {code} = await assigningRoles(data);
  if (code === 200){
    dialogRoleVisible.value = false;
    getfindAllSysUser();
    ElMessage.success("操作成功");
  }
}

</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>